﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.CrmContacto.Code;
using Web.Framework;
using CrmContacto.Contracts.Contracts.Search;
using CrmContacto.Contracts;
using CrmContacto.Contracts.Enums;
using Web.Framework.Translate;
using CrmContacto.Contracts.Contracts;
using CrmContacto.WebApp.Code.InnerClasses;
using Web.CrmContacto.Code.Security;
using Web.Framework.Helpers;

namespace CrmContacto.WebApp.App
{
    public partial class CustomerBitacora : BasePage
    {
        private Cliente currentCliente
        {
            get
            {
                return (Cliente)(ViewState["currentCliente"]);
            }
            set
            {
                ViewState["currentCliente"] = value;
            }
        }


        private List<LinkButton> actionButtons = new List<LinkButton>();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            LinkButton guardarButton = new LinkButton();
            guardarButton.ID = "BoCommandGuardar";
            guardarButton.Text = LocalizationProvider.Instance["Bo.Command.Guardar"];
            guardarButton.Click += new EventHandler(lnkGuardar_Click);
            actionButtons.Add(guardarButton);
            
            LinkButton volverButton = new LinkButton();
            volverButton.ID = "BoCommandVolver";
            volverButton.Text = LocalizationProvider.Instance["Bo.Command.Volver"];
            volverButton.Click += new EventHandler(lnkVolver_Click);
            SetJavascriptForClientClickDirtyChech(volverButton);
            actionButtons.Add(volverButton);

            base.LoadContextActions(actionButtons);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                HasPermissionToSeeMe(CrmSecurity.CUSTOMER_ADD_BITACORA);

                if (!this.IsPostBack)
                {
                    if (this.Request["ContactoId"] == null)
                        throw new ArgumentNullException("ContactoId");

                    int customerId = Convert.ToInt32(this.Request.QueryString["ContactoId"]);
                    currentCliente = WebServiceHelper.GetCustomerById(WebServiceHelper.ServiceOptionsDefault, customerId, new ClienteByIdOptions() { LoadBasicInfo = true, LoadSales = false, LoadBitacora = true });
                    LoadCbos();
                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void LoadCbos()
        {
            var tipoMensajeBitacoraList = WebServiceHelper.GetTipoMensajeBitacora(new TipoMensajeBitacoraSearch() { EmpresaId = BasePage.CompanyId,EsPdv = false });
            UIHelper.LoadCbo(tipoMensajeBitacoraList, cboTipoMensajeBitacoraId, LocalizationProvider.Instance["DropDown.SinEspecificar"]);            
        }

        private void Bind()
        {
            this.lblEmail.Text = currentCliente.Email;
            this.lblNombre.Text = currentCliente.Nombre;
            this.lblApellido.Text = currentCliente.Apellido;

            this.txtAccion.Text = string.Empty;

            UIHelper.LoadEstados<TipoRegistroBitacora>(this.cboTipoRegistroBitacora);
            this.cboTipoRegistroBitacora.SelectedValue = ((int)TipoRegistroBitacora.Mensaje).ToString();
            this.cboTipoRegistroBitacora.Enabled = false;

            BindBitacoraToGrid();
        }

        protected void lnkGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                SaveBitacoraRegistry();
                Bind();
                this.masterPage.ShowMessage(LocalizationProvider.Instance["Bo.Messages.MensajeSaveExitoso"], WebMessageType.Notification);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkVolver_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlCustomerEdit + string.Format("?Id={0}&tabName={1}", currentCliente.Id, (int)MiscClass.ClienteEditTab.Bitacora), true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void BindBitacoraToGrid()
        {
            this.GridBitacora.DataSource = currentCliente.Bitacora;
            this.GridBitacora.DataBind();
        }

        private void SaveBitacoraRegistry()
        {
            ClienteBitacora clienteBitacora = new ClienteBitacora();
            clienteBitacora.TipoRegistroBitacora = UIHelper.GetIntFromInputCbo(this.cboTipoRegistroBitacora).Value;
            clienteBitacora.Accion = this.txtAccion.Text;
            clienteBitacora.ContactoId = currentCliente.Id;
            clienteBitacora.TipoMensajeBitacoraId = UIHelper.GetIntFromInputCbo(this.cboTipoMensajeBitacoraId).Value;
            clienteBitacora.FechaCreacion = DateTime.Now;
            WebServiceHelper.SaveCustomerBitacora(clienteBitacora);

            currentCliente.Bitacora.Add(clienteBitacora);
        }

        protected void GridBitacora_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    //    int temporadaId = Convert.ToInt32(this.GridTemporadas.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    //    this.Response.Redirect(string.Format("/App/TemporadaEdit.aspx?Id={0}", temporadaId), true);
                }
                else if (e.CommandName == "eliminar")
                {
                    //int temporadaId = Convert.ToInt32(this.GridTemporadas.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    //WebServiceHelper.EliminarTemporada(temporadaId);
                    //StoreHelper.GetObject(this.Session, MiscClass.CustomerSearchCacheKey);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridBitacora_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                this.GridBitacora.PageIndex = e.NewPageIndex;
                BindBitacoraToGrid();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private List<TipoMensajeBitacora> tipoMensajeBitacoraList;
        private List<TipoMensajeBitacora> GetTipoMensajeBitacora()
        {
            if (tipoMensajeBitacoraList == null)
            {
                tipoMensajeBitacoraList = WebServiceHelper.GetTipoMensajeBitacora(new TipoMensajeBitacoraSearch() { EmpresaId = BasePage.CompanyId, EsPdv = false });                
            }

            return tipoMensajeBitacoraList;
        }

        protected void GridBitacora_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    ClienteBitacora clienteBitacoraItem = (ClienteBitacora)e.Row.DataItem;
                    e.Row.Cells[1].Text = UIHelper.GetEnumDescription((TipoRegistroBitacora)clienteBitacoraItem.TipoRegistroBitacora);
                    if (clienteBitacoraItem.TipoMensajeBitacoraId.HasValue)
                    {
                        e.Row.Cells[2].Text = GetTipoMensajeBitacora().Where(r => r.Id == clienteBitacoraItem.TipoMensajeBitacoraId.Value).Single().Nombre;
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkIrATipoMensaje_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.cboTipoMensajeBitacoraId.SelectedIndex >= 0)
                {
                    string tipoMensajeId = this.cboTipoMensajeBitacoraId.SelectedValue;

                    if (tipoMensajeId != UIHelper.cboNullValue)
                    {
                        this.NavigationContext.RedirectTo(MiscClass.UrlTipoMensajeBitacoraEdit, string.Format("?Id={0}", tipoMensajeId));
                    }
                    else
                    {
                        this.NavigationContext.RedirectTo(MiscClass.UrlTipoMensajeBitacoraList, string.Empty);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }        

        protected void lnkIrAContacto_Click(object sender, EventArgs e)
        {
            try
            {
                if (NavigationContext.ContactoId.HasValue)
                {
                    NavigationContext.Clear();
                    NavigationContext.RedirectTo(MiscClass.UrlCustomerEdit, string.Format("?Id={0}", NavigationContext.ContactoId.Value));
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkExportarAExcel_Click(object sender, EventArgs e)
        {
            try
            {
                bool previousAllowPaging = this.GridBitacora.AllowPaging;
                this.GridBitacora.AllowPaging = false;

                BindBitacoraToGrid();

                GridViewExportExcelUtil.Export("Bitacora.xls", this.GridBitacora, 0);

                this.GridBitacora.AllowPaging = previousAllowPaging;
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}